package com.shwread.address;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.logic.dao.AddressBookInfoDao;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.activity.TeamMessageActivity;
import com.netease.nimlib.sdk.team.model.Team;
import com.shwread.android.qysw.activity.ChatPersonalInfoActivity;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.dialog.ContactCallSelectDialog;
import com.shwread.android.ui.widget.CircleImageView;
import com.tgx.tina.android.ipc.framework.BaseActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import logic.bean.ContactInfo;
import logic.bean.GroupBean;
import logic.dao.GroupDao;
import logic.util.PicassoUtil;
import logic.util.Utils;

/**
 * 分层联系人界面
 */
public class AddressActivity extends BaseActivity implements OnClickListener {

    private Button btnBack;
    private ListView address_page_list;
    private TextView tv_no_address;
    private int groupId;
    private List<AddressBookInfo> contactResults;
    private GroupDao groupDao;
    private AddressBookInfoDao addressBookInfoDao;

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layere_address);
        context = this;
        groupId = getIntent().getIntExtra("groupId",-1);
        groupDao = GroupDao.getInstance(this);
        addressBookInfoDao = AddressBookInfoDao.getInstance(this);
        initView();
        initData();
        setLinstener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initData() {
        List<AddressBookInfo> addressList = addressBookInfoDao.getListByGroupId(groupId);
        contactResults = new ArrayList<>();
        if (addressList == null) {//无数据
            address_page_list.setVisibility(View.GONE);
            tv_no_address.setVisibility(View.VISIBLE);
            return;
        }
        for (AddressBookInfo info : addressList) {
            if (info.getIsDelete().equals("n")) {
                contactResults.add(info);
            }
        }
        if (contactResults.size() == 0) {//无数据
            address_page_list.setVisibility(View.GONE);
            tv_no_address.setVisibility(View.VISIBLE);
        } else {
            Collections.sort(contactResults,new Comparator<AddressBookInfo>() {
                @Override
                public int compare(AddressBookInfo info1, AddressBookInfo info2) {
                    return info1.getSortNum() - info2.getSortNum();
                }
            });
            tv_no_address.setVisibility(View.GONE);
            address_page_list.setVisibility(View.VISIBLE);
            //填充数据
            ContactAdapter contactAdapter = new ContactAdapter();
            address_page_list.setAdapter(contactAdapter);
        }
    }

    private void setLinstener() {
        btnBack.setOnClickListener(this);
    }

    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText("联系人");
        btnBack = (Button) findViewById(R.id.common_header_back);//返回
        btnBack.setVisibility(View.VISIBLE);
        address_page_list = (ListView) findViewById(R.id.address_page_list);//列表
        tv_no_address = (TextView) findViewById(R.id.tv_no_address);  //无联系人
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back://返回
                finish();
                break;
            default:
                break;
        }
    }

    private class ContactAdapter extends BaseAdapter {
        ViewHolder holder;

        @Override
        public int getCount() {
            return contactResults.size();
        }

        @Override
        public Object getItem(int position) {
            return contactResults.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.chat_contact_item, null);
                holder.contactsHeadImg = (CircleImageView) convertView.findViewById(R.id.iv_chat_head_img);
                holder.contactsHeader = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_header);
                holder.contactsCall = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_call);
                holder.contactsMsg = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_msg);
                holder.contactsChat = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_chat);
                holder.contactsName = (TextView) convertView.findViewById(R.id.tv_chat_contact_name);
                holder.rlItem = (RelativeLayout) convertView.findViewById(R.id.rl_contact_item);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final AddressBookInfo addressBookInfo = contactResults.get(position);

            if (Utils.isNotEmpty(addressBookInfo.getUserHead())) {//头像
                PicassoUtil.load(context, addressBookInfo.getUserHead(), R.drawable.chat_head_img, holder.contactsHeadImg);
            } else {
//                PicassoUtil.load(context, R.drawable.chat_head_img, holder.contactsHeadImg);
                holder.contactsHeadImg.setImageResource(R.drawable.chat_head_img);
            }
            if (addressBookInfo.getGroupPosition() == 1) {//职务
                PicassoUtil.load(context, R.drawable.chat_contract_icon_header, holder.contactsHeader);
                holder.contactsHeader.setVisibility(View.VISIBLE);
            } else if (addressBookInfo.getGroupPosition() == 2) {
                PicassoUtil.load(context, R.drawable.chat_contract_icon_deputy_header, holder.contactsHeader);
                holder.contactsHeader.setVisibility(View.VISIBLE);
            } else {
                holder.contactsHeader.setVisibility(View.GONE);
            }
            holder.contactsName.setText(addressBookInfo.getContactName());
            if (Utils.isEmpty(addressBookInfo.getMobileNumber())) {
                holder.contactsMsg.setVisibility(View.GONE);
                holder.contactsChat.setVisibility(View.GONE);
            } else {
                holder.contactsMsg.setVisibility(View.VISIBLE);
                holder.contactsChat.setVisibility(View.VISIBLE);
            }
            holder.contactsMsg.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {//短信
                    if (Utils.isNotEmpty(addressBookInfo.getMobileNumber())) {
                        doSendSMSTo(addressBookInfo.getMobileNumber(), null);
                    }
                }
            });

            holder.contactsCall.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {//拨号
                    List<String> phoneList = new ArrayList<>();
                    if (Utils.isNotEmpty(addressBookInfo.getMobileNumber())) {
                        phoneList.add(addressBookInfo.getMobileNumber());
                    }
                    if (Utils.isNotEmpty(addressBookInfo.getPhoneNumber())) {
                        phoneList.add(addressBookInfo.getPhoneNumber());
                    }
                    ContactCallSelectDialog selectNum = new ContactCallSelectDialog(context, phoneList);
                    if (phoneList.size() > 1) {
                        selectNum.show();
                    } else {
                        dialPhoneNumber(phoneList.get(0));
                    }
                }
            });

            holder.contactsChat.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {//聊天
                    ContactInfo info = new ContactInfo();
                    info.setAccId(addressBookInfo.getAccId());
                    info.setAccount(addressBookInfo.getMobileNumber());
                    info.setHeadImage(addressBookInfo.getUserHead());
                    info.setStaffName(addressBookInfo.getContactName());
                    talkto(info);
                }
            });
            holder.rlItem.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, ChatPersonalInfoActivity.class);
                    intent.putExtra("contactInfo", addressBookInfo);
                    GroupBean group = groupDao.getById(addressBookInfo.getGroupId());
                    String groupName = group.getName();
                    intent.putExtra("groupName", groupName);
                    context.startActivity(intent);
                }
            });
            return convertView;
        }

    }

    private static class ViewHolder {
        CircleImageView contactsHeadImg;
        ImageView contactsHeader, contactsCall, contactsMsg, contactsChat;
        TextView contactsName;
        RelativeLayout rlItem;
    }

    /**
     * 跳转到聊天页面
     */
    protected void talkto(Object item) {
        if (item instanceof ContactInfo) {
            ContactInfo info = (ContactInfo) item;
            String str;
            if (Utils.isNotEmpty(info.getStaffName())) {
                str = info.getStaffName();
            } else if (Utils.isNotEmpty(info.getNickName())) {
                str = info.getNickName();
            } else {
                str = info.getAccount();
            }
            P2PMessageActivity.start(context, info.getAccId(), str);
        } else if (item instanceof Team) {
            Team team = (Team) item;
            TeamMessageActivity.start(context, team.getId());
        }

    }

    /**
     * 调起系统发短信功能
     */
    private void doSendSMSTo(String phoneNumber, String message) {
        if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
            intent.putExtra("sms_body", message);
            context.startActivity(intent);
        }
    }

    /**
     * 调起系统拨号盘
     */
    private void dialPhoneNumber(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phoneNumber));
        context.startActivity(intent);
    }
}
